#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/7/26 17:15
from typing import List

from infrastructure.constant.response_constant import ResponseConstant
from infrastructure.rules.validators.validator_interface import ValidatorInterface
from infrastructure.utils.result_wrap import ResponseWrapper


class FormRule:
    def __init__(self, name:str, label:str, required:bool, validator:ValidatorInterface):
        assert name is not None and isinstance(name, str) \
               and label is not None and isinstance(label, str) \
               and required is not None and isinstance(required, bool) \
               and validator is not None
        if isinstance(validator, list) and len(validator) > 0:
            for vali in validator:
                assert isinstance(vali, ValidatorInterface)
        else:
            assert isinstance(validator, ValidatorInterface)
        self.name = name
        self.label = label
        self.required = required
        self.validator = validator

    def validate(self, value) -> ResponseWrapper:
        if isinstance(self.validator, list) and len(self.validator) > 0:
            for vali in self.validator:
                result:ResponseWrapper = vali.validate(value)
                if result.code != ResponseConstant.SUCCESS:
                    return result
        else:
            result = self.validator.validate(value)
            if result.code != ResponseConstant.SUCCESS:
                return result
        return ResponseWrapper.success()